package com.bluesky.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Function;

@Slf4j
public class defaultDistributeLock implements DistributeLock{

    private static ReentrantLock reentrantLock = new ReentrantLock();

    @Override
    public boolean accept(String lockKey, Consumer<String> consumer) {
        Objects.requireNonNull(consumer);
        Objects.requireNonNull(lockKey);

        boolean flag = reentrantLock.tryLock();
        try{
            if (log.isInfoEnabled()){
                log.info("get locak :[{}],[{}]",lockKey,flag);
            }
            if (!flag){
                return false;
            }
            consumer.accept(lockKey);
        }finally {
            if (flag){
                reentrantLock.unlock();
            }
        }
        return true;
    }

    @Override
    public void accept(String lockKey, Consumer<String> consumer, Function<String, ? extends RuntimeException> lockFailException) {

        Objects.requireNonNull(lockKey);
        Objects.requireNonNull(consumer);
        Objects.requireNonNull(lockFailException);

        boolean flag = this.accept(lockKey,consumer);
        if (!flag){
            throw lockFailException.apply(lockKey);
        }
    }
}
